package com.yingdong.sceneserver.net;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yingdong.sceneserver.SceneServer;
import com.yingdong.sceneserver.opcode.Dispatcher;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class SceneServerHandlerNetty4 extends ChannelInboundHandlerAdapter {

	static Log logger = LogFactory.getLog(SceneServerHandlerNetty4.class);

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Dispatcher.sceneServerSession = ctx.channel();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		while (true) {
			SceneServer.getInstance().reconnectGateserver();
			if (Dispatcher.sceneServerSession.isActive()) {
				break;
			}
			logger.info("与网关服务器连接关闭,1秒后重连!!");
			Thread.sleep(1000);

		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buffer = (ByteBuf) msg;
		try {
			Dispatcher.receiveBuffers.add(buffer);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			logger.debug(e1.getStackTrace());
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		//logger.info("", cause);
	}

}
